import React from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Upload, message } from 'antd';

class Up extends React.Component {
    constructor() {
        super()
        this.state = {
            loading: false,
            imgUrl: ""
        };
    }


    handleChange = info => {
        // 文件正在上传时触发
        if (info.file.status === 'uploading') {
            // 加载动画开启
            this.setState({ loading: true });
            return;
        }
        // 文件上传结束时触发
        if (info.file.status === 'done') {
            // 加载动画结束
            this.setState({
                loading: false,
                imgUrl: info.file.response.headimgurl
            });
            // 将图片地址回传给FromItem的关键函数
            this.props.onChange(this.state.imgUrl)
        }
    };



    // 限定文件格式和大小函数
    beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('你只能上传JPG/PNG文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片不能大于2MB!');
        }
        return isJpgOrPng && isLt2M;
    }



    render() {
        const { loading, imgUrl } = this.state;
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );

        return (
            <Upload
                name="headimgurl"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="api/students/uploadStuAvatar" // 跨域问题已解决
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
            >
                {imgUrl ? <img src={imgUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
        );
    }
}

export default Up;